/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.activity.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ykht.proj.activity.Enum.CardStatusEnum;
import com.ykht.proj.activity.Enum.EffectiveTypeEnum;
import com.ykht.proj.activity.Enum.PlanStatusEnum;
import com.ykht.proj.activity.entity.VCardGroup;
import com.ykht.proj.activity.entity.VCardLab;
import com.ykht.proj.activity.entity.VGroup;
import com.ykht.proj.activity.service.VOrderCardService;
import com.ykht.proj.activity.vo.VCardInfo;
import com.ykht.proj.activity.vo.VCardInfo4PC;
import com.ykht.proj.activity.vo.VCardVo;
import com.ykht.proj.activity.vo.VOrderCardVo;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.log.annotation.SysLog;
import com.ykht.proj.activity.entity.VCard;
import com.ykht.proj.activity.service.VCardService;
import com.ykht.proj.coupon.Enum.DelFlagEnum;
import com.ykht.proj.coupon.vo.BaseLonLat;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 卡表
 *
 * @author csg
 * @date 2021-05-21 14:21:47
 */
@RestController
@AllArgsConstructor
@RequestMapping("/vcard")
@Api(value = "vcard", tags = "卡表管理")
@Slf4j
public class VCardController {

	private final VCardService vCardService;

	@ApiOperation(value = "卡详情")
	@GetMapping("info/{id}" )
	public R<VCardInfo4PC> info(@PathVariable("id" ) Long id) {
		log.info("->pc卡详情{},{}",id);
		return R.ok(vCardService.getCardInfo4PC(id));
	}

	/**
	 * 卡列表分页查询
	 *
	 * @param page    分页对象
	 * @param vCardVo 卡表
	 * @return
	 */
	@ApiOperation(value = "卡列表分页查询", notes = "卡列表分页查询")
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('activity_vcard_view')")
	public R getVCardPage(Page page, VCardVo vCardVo) {
		log.info("->卡列表分页查询{}{}", page, vCardVo);
		QueryWrapper<VCard> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(VCard::getDelFlag, DelFlagEnum.usable.getValue())
				.like(!StringUtils.isEmpty(vCardVo.getName()), VCard::getName, vCardVo.getName())
				.eq(null != vCardVo.getType(),
						VCard::getType, vCardVo.getType())
				.eq(null != vCardVo.getUseEffectiveType(),
						VCard::getUseEffectiveType, vCardVo.getUseEffectiveType())
				.lt(null != vCardVo.getEndTime(), VCard::getEndTime, vCardVo.getEndTime())
				.gt(null != vCardVo.getStaTime(), VCard::getStaTime, vCardVo.getStaTime())
				.lt(null != vCardVo.getEndEffectiveDays(), VCard::getEffectiveDays, vCardVo.getEndEffectiveDays())
				.gt(null != vCardVo.getStaEffectiveDays(), VCard::getEffectiveDays, vCardVo.getStaEffectiveDays())
				.orderByDesc(VCard::getCreateTime);
		return R.ok(vCardService.page(page, queryWrapper));
	}


	/**
	 * 获取创建活动的 卡列表分页查询
	 *
	 * @param page    分页对象
	 * @param vCardVo 卡表
	 * @return
	 */
	@ApiOperation(value = "获取创建活动的 卡列表分页查询", notes = "获取创建活动的 卡列表分页查询")
	@GetMapping("/getByActivityAndCardPage")
	public R getByActivityAndCardPage(Page page, VCardVo vCardVo) {
		log.info("->获取创建活动的 卡列表分页查询{}{}", page, vCardVo);
		IPage<VCardVo> voIPage = vCardService.getByActivityAndCardPage(page, vCardVo);
		List<VCardVo> cardVoList = voIPage.getRecords();
		if (null != cardVoList && cardVoList.size() > 0) {
			cardVoList.stream().forEach(itme -> {
				itme.setUseType(itme.getUseTypeShow().contains("1") ? 1 : 0);
			});
			voIPage.setRecords(cardVoList);
		}
		return R.ok(voIPage);
	}

	/**
	 * 获取企业购买卡 列表分页查询
	 *
	 * @param page    分页对象
	 * @param vCardVo 卡表
	 * @return
	 */
	@ApiOperation(value = "获取企业购买卡 列表分页查询", notes = "获取企业购买卡 列表分页查询")
	@GetMapping("/getEntBuyCardPage")
	public R getEntBuyCardPage(Page page, VCardVo vCardVo) {
		log.info("->获取企业购买卡 列表分页查询{}{}", page, vCardVo);
		IPage<VCardVo> voIPage = vCardService.getEntBuyCardPage(page, vCardVo);
		return R.ok(voIPage);
	}


	/**
	 * 通过id查询卡表
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('activity_vcard_view')")
	public R getById(@PathVariable("id") Long id) {
		VCard card = vCardService.getById(id);
		VCardVo vCardVo = BeanUtil.toBean(card, VCardVo.class);
		List<VCardGroup> cardGroupList = new VCardGroup().selectList(Wrappers.lambdaQuery(VCardGroup.class)
				.eq(VCardGroup::getCardId, id));
		List<Long> groupIds = cardGroupList.stream().map(VCardGroup::getGroupId).collect(Collectors.toList());
		vCardVo.setGroupIds(groupIds);
		List<VGroup> groupList = new VGroup().selectList(Wrappers.lambdaQuery(VGroup.class)
				.in(VGroup::getId, groupIds));
		vCardVo.setGroupIdName(groupList);
		List<VCardLab> cardLabList = new VCardLab().selectList(Wrappers.lambdaQuery(VCardLab.class)
				.eq(VCardLab::getCardId, id));
		vCardVo.setLabelIds(cardLabList.stream().map(VCardLab::getLabelId).collect(Collectors.toList()));
		return R.ok(vCardVo);
	}

	/**
	 * 新增卡表
	 *
	 * @param vCardVo 卡表
	 * @return R
	 */
	@ApiOperation(value = "新增卡表", notes = "新增卡表")
	@SysLog("新增卡表")
	@PostMapping
//    @PreAuthorize("@pms.hasPermission('activity_vcard_add')" )
	public R save(@RequestBody VCardVo vCardVo) {
		log.info("->新增卡表{}", vCardVo);
		if (null != vCardVo.getSaleEndTime() && vCardVo.getSaleEndTime().isBefore(LocalDateTime.now())) {
			return R.failed("卡片结束时间要大于当前日期");
		}
		if (vCardVo.getUseEffectiveType().equals(EffectiveTypeEnum.TYPE_1.getValue())
				&& vCardVo.getEndTime().isBefore(LocalDateTime.now())) {
			return R.failed(" 使用有效期卡片结束时间要大于当前日期");
		}
		// 状态是上架中，把结束时间改成  2099
		if (vCardVo.getCardStatus().equals(CardStatusEnum.AT_WORK.getValue())) {
			vCardVo.setSaleStaTime(LocalDateTime.now());
			vCardVo.setSaleEndTime(LocalDateTime.of(2099, 12, 31, 23, 59, 59));
		}
		// 预约上架当当前时间  给状态改成上架中
		if (vCardVo.getCardStatus().equals(CardStatusEnum.TO_START.getValue())) {
			if (!LocalDateTime.now().isBefore(vCardVo.getSaleStaTime())) {
				vCardVo.setCardStatus(CardStatusEnum.AT_WORK.getValue());
			}
		}
		if (null == vCardVo.getGroupIds() || vCardVo.getGroupIds().size() == 0) {
			return R.failed("请选择参加卡的群组");
		}
		if (null == vCardVo.getLabelIds() || vCardVo.getLabelIds().size() == 0) {
			return R.failed("请选择卡的标签");
		}
		vCardService.addCard(vCardVo);
		return R.ok();
	}


	/**
	 * 修改卡表
	 *
	 * @param vCardVo 卡表
	 * @return R
	 */
	@ApiOperation(value = "修改卡表", notes = "修改卡表")
	@SysLog("修改卡表")
	@PutMapping
//	@PreAuthorize("@pms.hasPermission('activity_vcard_edit')")
	public R updateById(@RequestBody VCardVo vCardVo) {
		log.info("->修改卡表{}", vCardVo);
		if (null != vCardVo.getSaleEndTime() && vCardVo.getSaleEndTime().isBefore(LocalDateTime.now())) {
			return R.failed("卡片结束时间要大于当前日期");
		}
		// 状态是上架中，把结束时间改成  2099
		if (vCardVo.getCardStatus().equals(CardStatusEnum.AT_WORK.getValue())) {
			vCardVo.setSaleStaTime(LocalDateTime.now());
			vCardVo.setSaleEndTime(LocalDateTime.of(2099, 12, 31, 23, 59, 59));
		}
		// 预约上架当当前时间  给状态改成上架中
		if (vCardVo.getCardStatus().equals(CardStatusEnum.TO_START.getValue())) {
			if (!LocalDateTime.now().isBefore(vCardVo.getSaleStaTime())) {
				vCardVo.setCardStatus(CardStatusEnum.AT_WORK.getValue());
			}
		}
		if (null == vCardVo.getGroupIds() || vCardVo.getGroupIds().size() == 0) {
			return R.failed("请选择参加卡的群组");
		}
		if (null == vCardVo.getLabelIds() || vCardVo.getLabelIds().size() == 0) {
			return R.failed("请选择卡的标签");
		}
		vCardService.updateCard(vCardVo);
		return R.ok();
	}

	/**
	 * 添加库存（加减库存）
	 *
	 * @param vCardVo 卡表
	 * @return R
	 */
	@ApiOperation(value = "添加库存（加减库存）", notes = "添加库存（加减库存）")
	@SysLog("添加库存（加减库存）")
	@PostMapping("addStockNumber")
	public R addStockNumber(@RequestBody VCardVo vCardVo) {
		log.info("->添加库存（加减库存）{}", vCardVo);
		if (vCardVo.getStockNumber() == null) {
			return R.failed("加减库存 不能为空");
		}
		vCardVo.setStockNumber(vCardVo.getAddStockNumberType().equals(2) ?
				-vCardVo.getStockNumber() : vCardVo.getStockNumber());
		vCardService.addStockNumber(vCardVo);
		return R.ok();
	}

	/**
	 * 通过id删除卡表
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除卡表", notes = "通过id删除卡表")
	@SysLog("通过id删除卡表")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('activity_vcard_del')")
	public R removeById(@PathVariable Long id) {
		return R.ok(vCardService.removeById(id));
	}


	@ApiOperation(value = "校验 卡名称和排序")
	@PostMapping("/checkPlanName")
	public R checkSjName(@RequestBody VCard vCard) {
		log.info("->校验 卡名称和排序{}", vCard);
		VCard card = new VCard().selectOne(Wrappers.lambdaQuery(VCard.class)
				.eq(!StringUtils.isEmpty(vCard.getName()), VCard::getName, vCard.getName())
				.eq(null != vCard.getSort(), VCard::getSort, vCard.getSort()));
		return R.ok(card == null ? true : card.getId().equals(vCard.getId()) ? true : false);
	}

	@ApiOperation(value = "通过id修改分销", notes = "通过id修改分销")
	@GetMapping
	public R UpdateFxFlag(Long id, Integer fxFlag, BigDecimal returnPercentage ) {
		returnPercentage = returnPercentage.divide(BigDecimal.valueOf(100));
		return R.ok(vCardService.UpdateFxFlag(id,fxFlag,returnPercentage));
	}

}
